/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.datalogging.filter;

import java.util.Hashtable;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.BaseOpenmrsObject;
import org.openmrs.module.datalogging.configuration.Variable;
import org.openmrs.module.datalogging.handler.variable.VariableHandler;
import org.openmrs.module.datalogging.handler.variable.VariableHandlerFactory;

/**
 *
 */
public class FilterUtils {
	
	private static final Log log = LogFactory.getLog(FilterUtils.class);
	
	public static final String EXPRESSION_SEPARATOR = ";";
	
	public static final String KEY_SEPARATOR = "=";
	
	public static final String VALUE_SEPARATOR = ",";

	public static final String PROPERTY_SEPARATOR = ".";

	public static final String RULE_STRING = "logic";

	private FilterUtils() {
		// this class should not be instantiated
	}
	
	public static Map<String, Set<BaseOpenmrsObject>> parseFilter(Variable variable) {
		Map<String, Set<BaseOpenmrsObject>> filters = new Hashtable<String, Set<BaseOpenmrsObject>>();
		// filter expression:
		// - key1=key1value1,key1value2,key1value3;key2=key2value1,key2value2,key2value3
		VariableHandler variableHandler = VariableHandlerFactory.getHandler(variable.getVariableType());
		String[] filterExpressions = StringUtils.split(variable.getFilterExpression(), EXPRESSION_SEPARATOR);
		for (String filterExpression : filterExpressions) {
			String filterKey = filterExpression.substring(0, filterExpression.indexOf(KEY_SEPARATOR));
			if (variableHandler.supportFilter(filterKey)) {
				Filter filterHandler = FilterFactory.getHandler(filterKey);
				Set<BaseOpenmrsObject> objects = new LinkedHashSet<BaseOpenmrsObject>();
				String[] filterValues = StringUtils.split(filterExpression.substring(filterExpression.indexOf(KEY_SEPARATOR) + 1), VALUE_SEPARATOR);
				for (String value : filterValues) {
					try {
						BaseOpenmrsObject object = (BaseOpenmrsObject) filterHandler.getFilterValue(value);
						if (object != null)
							objects.add(object);
					} catch (Exception e) {
						log.error("Error parsing filter for : " + value + " ...", e);
					}
				}
				filters.put(filterKey, objects);
			}
		}
		
		return filters;
	}
	
}
